package com.wsl.mq;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.MessageTransformer;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsMessagingTemplate;

import javax.jms.*;

/**
 * @Author:WangShuliang
 * @Description:
 * @Date:Created in 13:57 2018/1/10
 * @Modified by:
 */
@Configuration
public class Producer {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 消息目的地
     * @param destination  消息目的地
     * @param message   发送消息的内容
     */
    public void sendWang(String destination,String message){
        jmsMessagingTemplate.convertAndSend(destination,message);
    }
    public Producer(ActiveMQConnectionFactory factory) {
        factory.setTransformer(new MessageTransformer() {
            @Override
            public Message producerTransform(Session session, MessageProducer messageProducer, Message message) throws JMSException {
                ActiveMQQueue activeMQQueue =(ActiveMQQueue)messageProducer.getDestination();
                StringBuffer stringBuffer = new StringBuffer(messageProducer.toString().substring(32,messageProducer.toString().length()-2));
                stringBuffer.append(":1").replace(0,2,activeMQQueue.getQueueName());
                if (message instanceof ActiveMQTextMessage){
                    ActiveMQTextMessage message1 = (ActiveMQTextMessage)message;
                    Producer.this.redisTemplate.opsForHash().put("MQWANG",stringBuffer.toString(),message1.getText());

                }
                if (message instanceof ActiveMQObjectMessage){
                    ActiveMQObjectMessage mqObjectMessage = (ActiveMQObjectMessage)message;
                    Producer.this.redisTemplate.opsForHash().put("MQWANG",stringBuffer.toString(),mqObjectMessage.getObject());
                }
                return message;
            }

            @Override
            public Message consumerTransform(Session session, MessageConsumer messageConsumer, Message message) throws JMSException {
                return message;
            }
        });
    }
}